home *** CD-ROM | disk | FTP | other *** search
/ Aminet 32 / Aminet 32 (1999)(Schatztruhe)[!][Aug 1999].iso / Aminet / dev / lang / Python151_Src.lha / Python1.5_Source / Modules / structmodule.c < prev    next >
C/C++ Source or Header  |  1998-05-26  |  26KB  |  1,344 lines

  1. /***********************************************************
  2. Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
  3. The Netherlands.
  4.  
  5.                         All Rights Reserved
  6.  
  7. Permission to use, copy, modify, and distribute this software and its
  8. documentation for any purpose and without fee is hereby granted,
  9. provided that the above copyright notice appear in all copies and that
  10. both that copyright notice and this permission notice appear in
  11. supporting documentation, and that the names of Stichting Mathematisch
  12. Centrum or CWI or Corporation for National Research Initiatives or
  13. CNRI not be used in advertising or publicity pertaining to
  14. distribution of the software without specific, written prior
  15. permission.
  16.  
  17. While CWI is the initial source for this software, a modified version
  18. is made available by the Corporation for National Research Initiatives
  19. (CNRI) at the Internet address ftp://ftp.python.org.
  20.  
  21. STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
  22. REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
  23. MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
  24. CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
  25. DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
  26. PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  27. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  28. PERFORMANCE OF THIS SOFTWARE.
  29.  
  30. ******************************************************************/
  31.  
  32. /* struct module -- pack values into and (out of) strings */
  33.  
  34. /* New version supporting byte order, alignment and size options,
  35.    character strings, and unsigned numbers */
  36.  
  37. static char struct__doc__[] = "\
  38. Functions to convert between Python values and C structs.\n\
  39. Python strings are used to hold the data representing the C struct\n\
  40. and also as format strings to describe the layout of data in the C struct.\n\
  41. \n\
  42. The optional first format char indicates byte ordering and alignment:\n\
  43.  @: native w/native alignment(default)\n\
  44.  =: native w/standard alignment\n\
  45.  <: little-endian, std. alignment\n\
  46.  >: big-endian, std. alignment\n\
  47.  !: network, std (same as >)\n\
  48. \n\
  49. The remaining chars indicate types of args and must match exactly;\n\
  50. these can be preceded by a decimal repeat count:\n\
  51.  x: pad byte (no data); c:char; b:signed byte; B:unsigned byte;\n\
  52.  h:short; H:unsigned short; i:int; I:unsigned int;\n\
  53.  l:long; L:unsigned long; f:float; d:double.\n\
  54. Special cases (preceding decimal count indicates length):\n\
  55.  s:string (array of char); p: pascal string (w. count byte).\n\
  56. Whitespace between formats is ignored.\n\
  57. \n\
  58. The variable struct.error is an exception raised on errors.";
  59.  
  60. #include "Python.h"
  61. #include "mymath.h"
  62.  
  63. #include <limits.h>
  64. #include <ctype.h>
  65.  
  66.  
  67. /* Exception */
  68.  
  69. static PyObject *StructError;
  70.  
  71. #include "protos/structmodule_protos1.h"
  72.  
  73. /* Define various structs to figure out the alignments of types */
  74.  
  75. #ifdef __MWERKS__
  76. /*
  77. ** XXXX We have a problem here. There are no unique alignment rules
  78. ** on the PowerPC mac. 
  79. */
  80. #ifdef __powerc
  81. #pragma options align=mac68k
  82. #endif
  83. #endif /* __MWERKS__ */
  84.  
  85. typedef struct { char c; short x; } s_short;
  86. typedef struct { char c; int x; } s_int;
  87. typedef struct { char c; long x; } s_long;
  88. typedef struct { char c; float x; } s_float;
  89. typedef struct { char c; double x; } s_double;
  90.  
  91. #define SHORT_ALIGN (sizeof(s_short) - sizeof(short))
  92. #define INT_ALIGN (sizeof(s_int) - sizeof(int))
  93. #define LONG_ALIGN (sizeof(s_long) - sizeof(long))
  94. #define FLOAT_ALIGN (sizeof(s_float) - sizeof(float))
  95. #define DOUBLE_ALIGN (sizeof(s_double) - sizeof(double))
  96.  
  97. #ifdef __powerc
  98. #pragma options align=reset
  99. #endif
  100.  
  101. /* Helper routine to get a Python integer and raise the appropriate error
  102.    if it isn't one */
  103.  
  104. static int
  105. get_long(v, p)
  106.     PyObject *v;
  107.     long *p;
  108. {
  109.     long x = PyInt_AsLong(v);
  110.     if (x == -1 && PyErr_Occurred()) {
  111.         if (PyErr_Occurred() == PyExc_TypeError)
  112.             PyErr_SetString(StructError,
  113.                     "required argument is not an integer");
  114.         return -1;
  115.     }
  116.     *p = x;
  117.     return 0;
  118. }
  119.  
  120.  
  121. /* Same, but handling unsigned long */
  122.  
  123. static int
  124. get_ulong(v, p)
  125.     PyObject *v;
  126.     unsigned long *p;
  127. {
  128.     if (PyLong_Check(v)) {
  129.         unsigned long x = PyLong_AsUnsignedLong(v);
  130.         if (x == (unsigned long)(-1) && PyErr_Occurred())
  131.             return -1;
  132.         *p = x;
  133.         return 0;
  134.     }
  135.     else {
  136.         return get_long(v, (long *)p);
  137.     }
  138. }
  139.  
  140.  
  141. /* Floating point helpers */
  142.  
  143. /* These use ANSI/IEEE Standard 754-1985 (Standard for Binary Floating
  144.    Point Arithmetic).  See the following URL:
  145.    http://www.psc.edu/general/software/packages/ieee/ieee.html */
  146.  
  147. /* XXX Inf/NaN are not handled quite right (but underflow is!) */
  148.  
  149. static int
  150. pack_float(x, p, incr)
  151.     double x; /* The number to pack */
  152.     char *p;  /* Where to pack the high order byte */
  153.     int incr; /* 1 for big-endian; -1 for little-endian */
  154. {
  155.     int s;
  156.     int e;
  157.     double f;
  158.     long fbits;
  159.  
  160.     if (x < 0) {
  161.         s = 1;
  162.         x = -x;
  163.     }
  164.     else
  165.         s = 0;
  166.  
  167.     f = frexp(x, &e);
  168.  
  169.     /* Normalize f to be in the range [1.0, 2.0) */
  170.     if (0.5 <= f && f < 1.0) {
  171.         f *= 2.0;
  172.         e--;
  173.     }
  174.     else if (f == 0.0) {
  175.         e = 0;
  176.     }
  177.     else {
  178.         PyErr_SetString(PyExc_SystemError,
  179.                 "frexp() result out of range");
  180.         return -1;
  181.     }
  182.  
  183.     if (e >= 128) {
  184.         /* XXX 128 itself is reserved for Inf/NaN */
  185.         PyErr_SetString(PyExc_OverflowError,
  186.                 "float too large to pack with f format");
  187.         return -1;
  188.     }
  189.     else if (e < -126) {
  190.         /* Gradual underflow */
  191.         f = ldexp(f, 126 + e);
  192.         e = 0;
  193.     }
  194.     else if (!(e == 0 && f == 0.0)) {
  195.         e += 127;
  196.         f -= 1.0; /* Get rid of leading 1 */
  197.     }
  198.  
  199.     f *= 8388608.0; /* 2**23 */
  200.     fbits = (long) floor(f + 0.5); /* Round */
  201.  
  202.     /* First byte */
  203.     *p = (s<<7) | (e>>1);
  204.     p += incr;
  205.  
  206.     /* Second byte */
  207.     *p = (char) (((e&1)<<7) | (fbits>>16));
  208.     p += incr;
  209.  
  210.     /* Third byte */
  211.     *p = (fbits>>8) & 0xFF;
  212.     p += incr;
  213.  
  214.     /* Fourth byte */
  215.     *p = fbits&0xFF;
  216.  
  217.     /* Done */
  218.     return 0;
  219. }
  220.  
  221. static int
  222. pack_double(x, p, incr)
  223.     double x; /* The number to pack */
  224.     char *p;  /* Where to pack the high order byte */
  225.     int incr; /* 1 for big-endian; -1 for little-endian */
  226. {
  227.     int s;
  228.     int e;
  229.     double f;
  230.     long fhi, flo;
  231.  
  232.     if (x < 0) {
  233.         s = 1;
  234.         x = -x;
  235.     }
  236.     else
  237.         s = 0;
  238.  
  239.     f = frexp(x, &e);
  240.  
  241.     /* Normalize f to be in the range [1.0, 2.0) */
  242.     if (0.5 <= f && f < 1.0) {
  243.         f *= 2.0;
  244.         e--;
  245.     }
  246.     else if (f == 0.0) {
  247.         e = 0;
  248.     }
  249.     else {
  250.         PyErr_SetString(PyExc_SystemError,
  251.                 "frexp() result out of range");
  252.         return -1;
  253.     }
  254.  
  255.     if (e >= 1024) {
  256.         /* XXX 1024 itself is reserved for Inf/NaN */
  257.         PyErr_SetString(PyExc_OverflowError,
  258.                 "float too large to pack with d format");
  259.         return -1;
  260.     }
  261.     else if (e < -1022) {
  262.         /* Gradual underflow */
  263.         f = ldexp(f, 1022 + e);
  264.         e = 0;
  265.     }
  266.     else if (!(e == 0 && f == 0.0)) {
  267.         e += 1023;
  268.         f -= 1.0; /* Get rid of leading 1 */
  269.     }
  270.  
  271.     /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
  272.     f *= 268435456.0; /* 2**28 */
  273.     fhi = (long) floor(f); /* Truncate */
  274.     f -= (double)fhi;
  275.     f *= 16777216.0; /* 2**24 */
  276.     flo = (long) floor(f + 0.5); /* Round */
  277.  
  278.     /* First byte */
  279.     *p = (s<<7) | (e>>4);
  280.     p += incr;
  281.  
  282.     /* Second byte */
  283.     *p = (char) (((e&0xF)<<4) | (fhi>>24));
  284.     p += incr;
  285.  
  286.     /* Third byte */
  287.     *p = (fhi>>16) & 0xFF;
  288.     p += incr;
  289.  
  290.     /* Fourth byte */
  291.     *p = (fhi>>8) & 0xFF;
  292.     p += incr;
  293.  
  294.     /* Fifth byte */
  295.     *p = fhi & 0xFF;
  296.     p += incr;
  297.  
  298.     /* Sixth byte */
  299.     *p = (flo>>16) & 0xFF;
  300.     p += incr;
  301.  
  302.     /* Seventh byte */
  303.     *p = (flo>>8) & 0xFF;
  304.     p += incr;
  305.  
  306.     /* Eighth byte */
  307.     *p = flo & 0xFF;
  308.     p += incr;
  309.  
  310.     /* Done */
  311.     return 0;
  312. }
  313.  
  314. static PyObject *
  315. unpack_float(p, incr)
  316.     char *p;  /* Where the high order byte is */
  317.     int incr; /* 1 for big-endian; -1 for little-endian */
  318. {
  319.     int s;
  320.     int e;
  321.     long f;
  322.     double x;
  323.  
  324.     /* First byte */
  325.     s = (*p>>7) & 1;
  326.     e = (*p & 0x7F) << 1;
  327.     p += incr;
  328.  
  329.     /* Second byte */
  330.     e |= (*p>>7) & 1;
  331.     f = (*p & 0x7F) << 16;
  332.     p += incr;
  333.  
  334.     /* Third byte */
  335.     f |= (*p & 0xFF) << 8;
  336.     p += incr;
  337.  
  338.     /* Fourth byte */
  339.     f |= *p & 0xFF;
  340.  
  341.     x = (double)f / 8388608.0;
  342.  
  343.     /* XXX This sadly ignores Inf/NaN issues */
  344.     if (e == 0)
  345.         e = -126;
  346.     else {
  347.         x += 1.0;
  348.         e -= 127;
  349.     }
  350.     x = ldexp(x, e);
  351.  
  352.     if (s)
  353.         x = -x;
  354.  
  355.     return PyFloat_FromDouble(x);
  356. }
  357.  
  358. static PyObject *
  359. unpack_double(p, incr)
  360.     char *p;  /* Where the high order byte is */
  361.     int incr; /* 1 for big-endian; -1 for little-endian */
  362. {
  363.     int s;
  364.     int e;
  365.     long fhi, flo;
  366.     double x;
  367.  
  368.     /* First byte */
  369.     s = (*p>>7) & 1;
  370.     e = (*p & 0x7F) << 4;
  371.     p += incr;
  372.  
  373.     /* Second byte */
  374.     e |= (*p>>4) & 0xF;
  375.     fhi = (*p & 0xF) << 24;
  376.     p += incr;
  377.  
  378.     /* Third byte */
  379.     fhi |= (*p & 0xFF) << 16;
  380.     p += incr;
  381.  
  382.     /* Fourth byte */
  383.     fhi |= (*p & 0xFF) << 8;
  384.     p += incr;
  385.  
  386.     /* Fifth byte */
  387.     fhi |= *p & 0xFF;
  388.     p += incr;
  389.  
  390.     /* Sixth byte */
  391.     flo = (*p & 0xFF) << 16;
  392.     p += incr;
  393.  
  394.     /* Seventh byte */
  395.     flo |= (*p & 0xFF) << 8;
  396.     p += incr;
  397.  
  398.     /* Eighth byte */
  399.     flo |= *p & 0xFF;
  400.     p += incr;
  401.  
  402.     x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
  403.     x /= 268435456.0; /* 2**28 */
  404.  
  405.     /* XXX This sadly ignores Inf/NaN */
  406.     if (e == 0)
  407.         e = -1022;
  408.     else {
  409.         x += 1.0;
  410.         e -= 1023;
  411.     }
  412.     x = ldexp(x, e);
  413.  
  414.     if (s)
  415.         x = -x;
  416.  
  417.     return PyFloat_FromDouble(x);
  418. }
  419.  
  420.  
  421. /* The translation function for each format character is table driven */
  422.  
  423. typedef struct _formatdef {
  424.     char format;
  425.     int size;
  426.     int alignment;
  427.     PyObject* (*unpack) Py_PROTO((const char *,
  428.                       const struct _formatdef *));
  429.     int (*pack) Py_PROTO((char *,
  430.                   PyObject *,
  431.                   const struct _formatdef *));
  432. } formatdef;
  433.  
  434.  
  435. #include "protos/structmodule_protos2.h"
  436.  
  437. static PyObject *
  438. nu_char(p, f)
  439.     const char *p;
  440.     const formatdef *f;
  441. {
  442.     return PyString_FromStringAndSize(p, 1);
  443. }
  444.  
  445. static PyObject *
  446. nu_byte(p, f)
  447.     const char *p;
  448.     const formatdef *f;
  449. {
  450.     return PyInt_FromLong((long) *(signed char *)p);
  451. }
  452.  
  453. static PyObject *
  454. nu_ubyte(p, f)
  455.     const char *p;
  456.     const formatdef *f;
  457. {
  458.     return PyInt_FromLong((long) *(unsigned char *)p);
  459. }
  460.  
  461. static PyObject *
  462. nu_short(p, f)
  463.     const char *p;
  464.     const formatdef *f;
  465. {
  466.     return PyInt_FromLong((long) *(short *)p);
  467. }
  468.  
  469. static PyObject *
  470. nu_ushort(p, f)
  471.     const char *p;
  472.     const formatdef *f;
  473. {
  474.     return PyInt_FromLong((long) *(unsigned short *)p);
  475. }
  476.  
  477. static PyObject *
  478. nu_int(p, f)
  479.     const char *p;
  480.     const formatdef *f;
  481. {
  482.     return PyInt_FromLong((long) *(int *)p);
  483. }
  484.  
  485. static PyObject *
  486. nu_uint(p, f)
  487.     const char *p;
  488.     const formatdef *f;
  489. {
  490.     unsigned int x = *(unsigned int *)p;
  491.     return PyLong_FromUnsignedLong((unsigned long)x);
  492. }
  493.  
  494. static PyObject *
  495. nu_long(p, f)
  496.     const char *p;
  497.     const formatdef *f;
  498. {
  499.     return PyInt_FromLong(*(long *)p);
  500. }
  501.  
  502. static PyObject *
  503. nu_ulong(p, f)
  504.     const char *p;
  505.     const formatdef *f;
  506. {
  507.     return PyLong_FromUnsignedLong(*(unsigned long *)p);
  508. }
  509.  
  510. static PyObject *
  511. nu_float(p, f)
  512.     const char *p;
  513.     const formatdef *f;
  514. {
  515.     float x;
  516.     memcpy((char *)&x, p, sizeof(float));
  517.     return PyFloat_FromDouble((double)x);
  518. }
  519.  
  520. static PyObject *
  521. nu_double(p, f)
  522.     const char *p;
  523.     const formatdef *f;
  524. {
  525.     double x;
  526.     memcpy((char *)&x, p, sizeof(double));
  527.     return PyFloat_FromDouble(x);
  528. }
  529.  
  530. static int
  531. np_byte(p, v, f)
  532.     char *p;
  533.     PyObject *v;
  534.     const formatdef *f;
  535. {
  536.     long x;
  537.     if (get_long(v, &x) < 0)
  538.         return -1;
  539.     *p = (char)x;
  540.     return 0;
  541. }
  542.  
  543. static int
  544. np_char(p, v, f)
  545.     char *p;
  546.     PyObject *v;
  547.     const formatdef *f;
  548. {
  549.     if (!PyString_Check(v) || PyString_Size(v) != 1) {
  550.         PyErr_SetString(StructError,
  551.                 "char format require string of length 1");
  552.         return -1;
  553.     }
  554.     *p = *PyString_AsString(v);
  555.     return 0;
  556. }
  557.  
  558. static int
  559. np_short(p, v, f)
  560.     char *p;
  561.     PyObject *v;
  562.     const formatdef *f;
  563. {
  564.     long x;
  565.     if (get_long(v, &x) < 0)
  566.         return -1;
  567.     * (short *)p = (short)x;
  568.     return 0;
  569. }
  570.  
  571. static int
  572. np_int(p, v, f)
  573.     char *p;
  574.     PyObject *v;
  575.     const formatdef *f;
  576. {
  577.     long x;
  578.     if (get_long(v, &x) < 0)
  579.         return -1;
  580.     * (int *)p = x;
  581.     return 0;
  582. }
  583.  
  584. static int
  585. np_uint(p, v, f)
  586.     char *p;
  587.     PyObject *v;
  588.     const formatdef *f;
  589. {
  590.     unsigned long x;
  591.     if (get_ulong(v, &x) < 0)
  592.         return -1;
  593.     * (unsigned int *)p = x;
  594.     return 0;
  595. }
  596.  
  597. static int
  598. np_long(p, v, f)
  599.     char *p;
  600.     PyObject *v;
  601.     const formatdef *f;
  602. {
  603.     long x;
  604.     if (get_long(v, &x) < 0)
  605.         return -1;
  606.     * (long *)p = x;
  607.     return 0;
  608. }
  609.  
  610. static int
  611. np_ulong(p, v, f)
  612.     char *p;
  613.     PyObject *v;
  614.     const formatdef *f;
  615. {
  616.     unsigned long x;
  617.     if (get_ulong(v, &x) < 0)
  618.         return -1;
  619.     * (unsigned long *)p = x;
  620.     return 0;
  621. }
  622.  
  623. static int
  624. np_float(p, v, f)
  625.     char *p;
  626.     PyObject *v;
  627.     const formatdef *f;
  628. {
  629.     float x = (float)PyFloat_AsDouble(v);
  630.     if (x == -1 && PyErr_Occurred()) {
  631.         PyErr_SetString(StructError,
  632.                 "required argument is not a float");
  633.         return -1;
  634.     }
  635.     memcpy(p, (char *)&x, sizeof(float));
  636.     return 0;
  637. }
  638.  
  639. static int
  640. np_double(p, v, f)
  641.     char *p;
  642.     PyObject *v;
  643.     const formatdef *f;
  644. {
  645.     double x = PyFloat_AsDouble(v);
  646.     if (x == -1 && PyErr_Occurred()) {
  647.         PyErr_SetString(StructError,
  648.                 "required argument is not a float");
  649.         return -1;
  650.     }
  651.     memcpy(p, (char *)&x, sizeof(double));
  652.     return 0;
  653. }
  654.  
  655. static formatdef native_table[] = {
  656.     {'x',    sizeof(char),    0,        NULL},
  657.     {'b',    sizeof(char),    0,        nu_byte,    np_byte},
  658.     {'B',    sizeof(char),    0,        nu_ubyte,    np_byte},
  659.     {'c',    sizeof(char),    0,        nu_char,    np_char},
  660.     {'s',    sizeof(char),    0,        NULL},
  661.     {'p',    sizeof(char),    0,        NULL},
  662.     {'h',    sizeof(short),    SHORT_ALIGN,    nu_short,    np_short},
  663.     {'H',    sizeof(short),    SHORT_ALIGN,    nu_ushort,    np_short},
  664.     {'i',    sizeof(int),    INT_ALIGN,    nu_int,        np_int},
  665.     {'I',    sizeof(int),    INT_ALIGN,    nu_uint,    np_uint},
  666.     {'l',    sizeof(long),    LONG_ALIGN,    nu_long,    np_long},
  667.     {'L',    sizeof(long),    LONG_ALIGN,    nu_ulong,    np_ulong},
  668.     {'f',    sizeof(float),    FLOAT_ALIGN,    nu_float,    np_float},
  669.     {'d',    sizeof(double),    DOUBLE_ALIGN,    nu_double,    np_double},
  670.     {0}
  671. };
  672.  
  673. static PyObject *
  674. bu_int(p, f)
  675.     const char *p;
  676.     const formatdef *f;
  677. {
  678.     long x = 0;
  679.     int i = f->size;
  680.     do {
  681.         x = (x<<8) | (*p++ & 0xFF);
  682.     } while (--i > 0);
  683.     i = 8*(sizeof(long) - f->size);
  684.     if (i) {
  685.         x <<= i;
  686.         x >>= i;
  687.     }
  688.     return PyInt_FromLong(x);
  689. }
  690.  
  691. static PyObject *
  692. bu_uint(p, f)
  693.     const char *p;
  694.     const formatdef *f;
  695. {
  696.     unsigned long x = 0;
  697.     int i = f->size;
  698.     do {
  699.         x = (x<<8) | (*p++ & 0xFF);
  700.     } while (--i > 0);
  701.     return PyLong_FromUnsignedLong(x);
  702. }
  703.  
  704. static PyObject *
  705. bu_float(p, f)
  706.     const char *p;
  707.     const formatdef *f;
  708. {
  709.     return unpack_float(p, 1);
  710. }
  711.  
  712. static PyObject *
  713. bu_double(p, f)
  714.     const char *p;
  715.     const formatdef *f;
  716. {
  717.     return unpack_double(p, 1);
  718. }
  719.  
  720. static int
  721. bp_int(p, v, f)
  722.     char *p;
  723.     PyObject *v;
  724.     const formatdef *f;
  725. {
  726.     long x;
  727.     int i;
  728.     if (get_long(v, &x) < 0)
  729.         return -1;
  730.     i = f->size;
  731.     do {
  732.         p[--i] = (char)x;
  733.         x >>= 8;
  734.     } while (i > 0);
  735.     return 0;
  736. }
  737.  
  738. static int
  739. bp_uint(p, v, f)
  740.     char *p;
  741.     PyObject *v;
  742.     const formatdef *f;
  743. {
  744.     unsigned long x;
  745.     int i;
  746.     if (get_ulong(v, &x) < 0)
  747.         return -1;
  748.     i = f->size;
  749.     do {
  750.         p[--i] = (char)x;
  751.         x >>= 8;
  752.     } while (i > 0);
  753.     return 0;
  754. }
  755.  
  756. static int
  757. bp_float(p, v, f)
  758.     char *p;
  759.     PyObject *v;
  760.     const formatdef *f;
  761. {
  762.     double x = PyFloat_AsDouble(v);
  763.     if (x == -1 && PyErr_Occurred()) {
  764.         PyErr_SetString(StructError,
  765.                 "required argument is not a float");
  766.         return -1;
  767.     }
  768.     return pack_float(x, p, 1);
  769. }
  770.  
  771. static int
  772. bp_double(p, v, f)
  773.     char *p;
  774.     PyObject *v;
  775.     const formatdef *f;
  776. {
  777.     double x = PyFloat_AsDouble(v);
  778.     if (x == -1 && PyErr_Occurred()) {
  779.         PyErr_SetString(StructError,
  780.                 "required argument is not a float");
  781.         return -1;
  782.     }
  783.     return pack_double(x, p, 1);
  784. }
  785.  
  786. static formatdef bigendian_table[] = {
  787.     {'x',    1,        0,        NULL},
  788.     {'b',    1,        0,        bu_int,        bp_int},
  789.     {'B',    1,        0,        bu_uint,    bp_int},
  790.     {'c',    1,        0,        nu_char,    np_char},
  791.     {'s',    1,        0,        NULL},
  792.     {'p',    1,        0,        NULL},
  793.     {'h',    2,        0,        bu_int,        bp_int},
  794.     {'H',    2,        0,        bu_uint,    bp_uint},
  795.     {'i',    4,        0,        bu_int,        bp_int},
  796.     {'I',    4,        0,        bu_uint,    bp_uint},
  797.     {'l',    4,        0,        bu_int,        bp_int},
  798.     {'L',    4,        0,        bu_uint,    bp_uint},
  799.     {'f',    4,        0,        bu_float,    bp_float},
  800.     {'d',    8,        0,        bu_double,    bp_double},
  801.     {0}
  802. };
  803.  
  804. static PyObject *
  805. lu_int(p, f)
  806.     const char *p;
  807.     const formatdef *f;
  808. {
  809.     long x = 0;
  810.     int i = f->size;
  811.     do {
  812.         x = (x<<8) | (p[--i] & 0xFF);
  813.     } while (i > 0);
  814.     i = 8*(sizeof(long) - f->size);
  815.     if (i) {
  816.         x <<= i;
  817.         x >>= i;
  818.     }
  819.     return PyInt_FromLong(x);
  820. }
  821.  
  822. static PyObject *
  823. lu_uint(p, f)
  824.     const char *p;
  825.     const formatdef *f;
  826. {
  827.     unsigned long x = 0;
  828.     int i = f->size;
  829.     do {
  830.         x = (x<<8) | (p[--i] & 0xFF);
  831.     } while (i > 0);
  832.     return PyLong_FromUnsignedLong(x);
  833. }
  834.  
  835. static PyObject *
  836. lu_float(p, f)
  837.     const char *p;
  838.     const formatdef *f;
  839. {
  840.     return unpack_float(p+3, -1);
  841. }
  842.  
  843. static PyObject *
  844. lu_double(p, f)
  845.     const char *p;
  846.     const formatdef *f;
  847. {
  848.     return unpack_double(p+7, -1);
  849. }
  850.  
  851. static int
  852. lp_int(p, v, f)
  853.     char *p;
  854.     PyObject *v;
  855.     const formatdef *f;
  856. {
  857.     long x;
  858.     int i;
  859.     if (get_long(v, &x) < 0)
  860.         return -1;
  861.     i = f->size;
  862.     do {
  863.         *p++ = (char)x;
  864.         x >>= 8;
  865.     } while (--i > 0);
  866.     return 0;
  867. }
  868.  
  869. static int
  870. lp_uint(p, v, f)
  871.     char *p;
  872.     PyObject *v;
  873.     const formatdef *f;
  874. {
  875.     unsigned long x;
  876.     int i;
  877.     if (get_ulong(v, &x) < 0)
  878.         return -1;
  879.     i = f->size;
  880.     do {
  881.         *p++ = (char)x;
  882.         x >>= 8;
  883.     } while (--i > 0);
  884.     return 0;
  885. }
  886.  
  887. static int
  888. lp_float(p, v, f)
  889.     char *p;
  890.     PyObject *v;
  891.     const formatdef *f;
  892. {
  893.     double x = PyFloat_AsDouble(v);
  894.     if (x == -1 && PyErr_Occurred()) {
  895.         PyErr_SetString(StructError,
  896.                 "required argument is not a float");
  897.         return -1;
  898.     }
  899.     return pack_float(x, p+3, -1);
  900. }
  901.  
  902. static int
  903. lp_double(p, v, f)
  904.     char *p;
  905.     PyObject *v;
  906.     const formatdef *f;
  907. {
  908.     double x = PyFloat_AsDouble(v);
  909.     if (x == -1 && PyErr_Occurred()) {
  910.         PyErr_SetString(StructError,
  911.                 "required argument is not a float");
  912.         return -1;
  913.     }
  914.     return pack_double(x, p+7, -1);
  915. }
  916.  
  917. static formatdef lilendian_table[] = {
  918.     {'x',    1,        0,        NULL},
  919.     {'b',    1,        0,        lu_int,        lp_int},
  920.     {'B',    1,        0,        lu_uint,    lp_int},
  921.     {'c',    1,        0,        nu_char,    np_char},
  922.     {'s',    1,        0,        NULL},
  923.     {'p',    1,        0,        NULL},
  924.     {'h',    2,        0,        lu_int,        lp_int},
  925.     {'H',    2,        0,        lu_uint,    lp_uint},
  926.     {'i',    4,        0,        lu_int,        lp_int},
  927.     {'I',    4,        0,        lu_uint,    lp_uint},
  928.     {'l',    4,        0,        lu_int,        lp_int},
  929.     {'L',    4,        0,        lu_uint,    lp_uint},
  930.     {'f',    4,        0,        lu_float,    lp_float},
  931.     {'d',    8,        0,        lu_double,    lp_double},
  932.     {0}
  933. };
  934.  
  935.  
  936. static const formatdef *
  937. whichtable(pfmt)
  938.     const char **pfmt;
  939. {
  940.     const char *fmt = (*pfmt)++; /* May be backed out of later */
  941.     switch (*fmt) {
  942.     case '<':
  943.         return lilendian_table;
  944.     case '>':
  945.     case '!': /* Network byte order is big-endian */
  946.         return bigendian_table;
  947.     case '=': { /* Host byte order -- different from native in aligment! */
  948.         int n = 1;
  949.         char *p = (char *) &n;
  950.         if (*p == 1)
  951.             return lilendian_table;
  952.         else
  953.             return bigendian_table;
  954.     }
  955.     default:
  956.         --*pfmt; /* Back out of pointer increment */
  957.         /* Fall through */
  958.     case '@':
  959.         return native_table;
  960.     }
  961. }
  962.  
  963.  
  964. /* Get the table entry for a format code */
  965.  
  966. static const formatdef *
  967. getentry(c, f)
  968.     int c;
  969.     const formatdef *f;
  970. {
  971.     for (; f->format != '\0'; f++) {
  972.         if (f->format == c) {
  973.             return f;
  974.         }
  975.     }
  976.     PyErr_SetString(StructError, "bad char in struct format");
  977.     return NULL;
  978. }
  979.  
  980.  
  981. /* Align a size according to a format code */
  982.  
  983. static int
  984. align(size, c, e)
  985.     int size;
  986.     int c;
  987.     const formatdef *e;
  988. {
  989.     if (e->format == c) {
  990.         if (e->alignment) {
  991.             size = ((size + e->alignment - 1)
  992.                 / e->alignment)
  993.                 * e->alignment;
  994.         }
  995.     }
  996.     return size;
  997. }
  998.  
  999.  
  1000. /* calculate the size of a format string */
  1001.  
  1002. static int
  1003. calcsize(fmt, f)
  1004.     const char *fmt;
  1005.     const formatdef *f;
  1006. {
  1007.     const formatdef *e;
  1008.     const char *s;
  1009.     char c;
  1010.     int size,  num, itemsize, x;
  1011.  
  1012.     s = fmt;
  1013.     size = 0;
  1014.     while ((c = *s++) != '\0') {
  1015.         if (isspace((int)c))
  1016.             continue;
  1017.         if ('0' <= c && c <= '9') {
  1018.             num = c - '0';
  1019.             while ('0' <= (c = *s++) && c <= '9') {
  1020.                 x = num*10 + (c - '0');
  1021.                 if (x/10 != num) {
  1022.                     PyErr_SetString(
  1023.                         StructError,
  1024.                         "overflow in item count");
  1025.                     return -1;
  1026.                 }
  1027.                 num = x;
  1028.             }
  1029.             if (c == '\0')
  1030.                 break;
  1031.         }
  1032.         else
  1033.             num = 1;
  1034.         
  1035.         e = getentry(c, f);
  1036.         if (e == NULL)
  1037.             return -1;
  1038.         itemsize = e->size;
  1039.         size = align(size, c, e);
  1040.         x = num * itemsize;
  1041.         size += x;
  1042.         if (x/itemsize != num || size < 0) {
  1043.             PyErr_SetString(StructError,
  1044.                                         "total struct size too long");
  1045.             return -1;
  1046.         }
  1047.     }
  1048.  
  1049.     return size;
  1050. }
  1051.  
  1052.  
  1053. static char calcsize__doc__[] = "\
  1054. calcsize(fmt) -> int\n\
  1055. Return size of C struct described by format string fmt.\n\
  1056. See struct.__doc__ for more on format strings.";
  1057.  
  1058. static PyObject *
  1059. struct_calcsize(self, args)
  1060.     PyObject *self; /* Not used */
  1061.     PyObject *args;
  1062. {
  1063.     char *fmt;
  1064.     const formatdef *f;
  1065.     int size;
  1066.  
  1067.     if (!PyArg_ParseTuple(args, "s", &fmt))
  1068.         return NULL;
  1069.     f = whichtable(&fmt);
  1070.     size = calcsize(fmt, f);
  1071.     if (size < 0)
  1072.         return NULL;
  1073.     return PyInt_FromLong((long)size);
  1074. }
  1075.  
  1076.  
  1077. static char pack__doc__[] = "\
  1078. pack(fmt, v1, v2, ...) -> string\n\
  1079. Return string containing values v1, v2, ... packed according to fmt.\n\
  1080. See struct.__doc__ for more on format strings.";
  1081.  
  1082. static PyObject *
  1083. struct_pack(self, args)
  1084.     PyObject *self; /* Not used */
  1085.     PyObject *args;
  1086. {
  1087.     const formatdef *f, *e;
  1088.     PyObject *format, *result, *v;
  1089.     char *fmt;
  1090.     int size, num;
  1091.     int i, n;
  1092.     char *s, *res, *restart, *nres;
  1093.     char c;
  1094.  
  1095.     if (args == NULL || !PyTuple_Check(args) ||
  1096.         (n = PyTuple_Size(args)) < 1)
  1097.         {
  1098.         PyErr_BadArgument();
  1099.         return NULL;
  1100.     }
  1101.     format = PyTuple_GetItem(args, 0);
  1102.     if (!PyArg_Parse(format, "s", &fmt))
  1103.         return NULL;
  1104.     f = whichtable(&fmt);
  1105.     size = calcsize(fmt, f);
  1106.     if (size < 0)
  1107.         return NULL;
  1108.     result = PyString_FromStringAndSize((char *)NULL, size);
  1109.     if (result == NULL)
  1110.         return NULL;
  1111.  
  1112.     s = fmt;
  1113.     i = 1;
  1114.     res = restart = PyString_AsString(result);
  1115.  
  1116.     while ((c = *s++) != '\0') {
  1117.         if (isspace((int)c))
  1118.             continue;
  1119.         if ('0' <= c && c <= '9') {
  1120.             num = c - '0';
  1121.             while ('0' <= (c = *s++) && c <= '9')
  1122.                    num = num*10 + (c - '0');
  1123.             if (c == '\0')
  1124.                 break;
  1125.         }
  1126.         else
  1127.             num = 1;
  1128.  
  1129.         e = getentry(c, f);
  1130.         if (e == NULL)
  1131.             goto fail;
  1132.         nres = restart + align((int)(res-restart), c, e);
  1133.         /* Fill padd bytes with zeros */
  1134.         while (res < nres)
  1135.             *res++ = '\0';
  1136.         if (num == 0 && c != 's')
  1137.             continue;
  1138.         do {
  1139.             if (c == 'x') {
  1140.                 /* doesn't consume arguments */
  1141.                 memset(res, '\0', num);
  1142.                 res += num;
  1143.                 break;
  1144.             }
  1145.             if (i >= n) {
  1146.                 PyErr_SetString(StructError,
  1147.                     "insufficient arguments to pack");
  1148.                 goto fail;
  1149.                 }
  1150.             v = PyTuple_GetItem(args, i++);
  1151.             if (v == NULL)
  1152.                 goto fail;
  1153.             if (c == 's') {
  1154.                 /* num is string size, not repeat count */
  1155.                 int n;
  1156.                 if (!PyString_Check(v)) {
  1157.                     PyErr_SetString(StructError,
  1158.                       "argument for 's' must be a string");
  1159.                     goto fail;
  1160.                 }
  1161.                 n = PyString_Size(v);
  1162.                 if (n > num)
  1163.                     n = num;
  1164.                 if (n > 0)
  1165.                     memcpy(res, PyString_AsString(v), n);
  1166.                 if (n < num)
  1167.                     memset(res+n, '\0', num-n);
  1168.                 res += num;
  1169.                 break;
  1170.             }
  1171.             else if (c == 'p') {
  1172.                 /* num is string size + 1,
  1173.                    to fit in the count byte */
  1174.                 int n;
  1175.                 num--; /* now num is max string size */
  1176.                 if (!PyString_Check(v)) {
  1177.                     PyErr_SetString(StructError,
  1178.                       "argument for 'p' must be a string");
  1179.                     goto fail;
  1180.                 }
  1181.                 n = PyString_Size(v);
  1182.                 if (n > num)
  1183.                     n = num;
  1184.                 if (n > 0)
  1185.                     memcpy(res+1, PyString_AsString(v), n);
  1186.                 if (n < num)
  1187.                     /* no real need, just to be nice */
  1188.                     memset(res+1+n, '\0', num-n);
  1189.                 *res++ = n; /* store the length byte */
  1190.                 res += num;
  1191.                 break;
  1192.             }
  1193.             else {
  1194.                 if (e->pack(res, v, e) < 0)
  1195.                     goto fail;
  1196.                 res += e->size;
  1197.             }
  1198.         } while (--num > 0);
  1199.     }
  1200.  
  1201.     if (i < n) {
  1202.         PyErr_SetString(StructError,
  1203.                 "too many arguments for pack format");
  1204.         goto fail;
  1205.     }
  1206.  
  1207.     return result;
  1208.  
  1209.  fail:
  1210.     Py_DECREF(result);
  1211.     return NULL;
  1212. }
  1213.  
  1214.  
  1215. static char unpack__doc__[] = "\
  1216. unpack(fmt, string) -> (v1, v2, ...)\n\
  1217. Unpack the string, containing packed C structure data, according\n\
  1218. to fmt.  Requires len(string)==calcsize(fmt).\n\
  1219. See struct.__doc__ for more on format strings.";
  1220.  
  1221. static PyObject *
  1222. struct_unpack(self, args)
  1223.     PyObject *self; /* Not used */
  1224.     PyObject *args;
  1225. {
  1226.     const formatdef *f, *e;
  1227.     char *str, *start, *fmt, *s;
  1228.     char c;
  1229.     int len, size, num;
  1230.     PyObject *res, *v;
  1231.  
  1232.     if (!PyArg_ParseTuple(args, "ss#", &fmt, &start, &len))
  1233.         return NULL;
  1234.     f = whichtable(&fmt);
  1235.     size = calcsize(fmt, f);
  1236.     if (size < 0)
  1237.         return NULL;
  1238.     if (size != len) {
  1239.         PyErr_SetString(StructError,
  1240.                 "unpack str size does not match format");
  1241.         return NULL;
  1242.     }
  1243.     res = PyList_New(0);
  1244.     if (res == NULL)
  1245.         return NULL;
  1246.     str = start;
  1247.     s = fmt;
  1248.     while ((c = *s++) != '\0') {
  1249.         if (isspace((int)c))
  1250.             continue;
  1251.         if ('0' <= c && c <= '9') {
  1252.             num = c - '0';
  1253.             while ('0' <= (c = *s++) && c <= '9')
  1254.                    num = num*10 + (c - '0');
  1255.             if (c == '\0')
  1256.                 break;
  1257.         }
  1258.         else
  1259.             num = 1;
  1260.  
  1261.         e = getentry(c, f);
  1262.         if (e == NULL)
  1263.             goto fail;
  1264.         str = start + align((int)(str-start), c, e);
  1265.         if (num == 0 && c != 's')
  1266.             continue;
  1267.  
  1268.         do {
  1269.             if (c == 'x') {
  1270.                 str += num;
  1271.                 break;
  1272.             }
  1273.             if (c == 's') {
  1274.                 /* num is string size, not repeat count */
  1275.                 v = PyString_FromStringAndSize(str, num);
  1276.                 if (v == NULL)
  1277.                     goto fail;
  1278.                 str += num;
  1279.                 num = 0;
  1280.             }
  1281.             else if (c == 'p') {
  1282.                 /* num is string buffer size,
  1283.                    not repeat count */
  1284.                 int n = *(unsigned char*)str;
  1285.                 /* first byte (unsigned) is string size */
  1286.                 if (n >= num)
  1287.                     n = num-1;
  1288.                 v = PyString_FromStringAndSize(str+1, n);
  1289.                 if (v == NULL)
  1290.                     goto fail;
  1291.                 str += num;
  1292.                 num = 0;
  1293.             }
  1294.             else {
  1295.                 v = e->unpack(str, e);
  1296.                 if (v == NULL)
  1297.                     goto fail;
  1298.                 str += e->size;
  1299.             }
  1300.             if (v == NULL || PyList_Append(res, v) < 0)
  1301.                 goto fail;
  1302.             Py_DECREF(v);
  1303.         } while (--num > 0);
  1304.     }
  1305.  
  1306.     v = PyList_AsTuple(res);
  1307.     Py_DECREF(res);
  1308.     return v;
  1309.  
  1310.  fail:
  1311.     Py_DECREF(res);
  1312.     return NULL;
  1313. }
  1314.  
  1315.  
  1316. /* List of functions */
  1317.  
  1318. static PyMethodDef struct_methods[] = {
  1319.     {"calcsize",    struct_calcsize,    METH_VARARGS, calcsize__doc__},
  1320.     {"pack",    struct_pack,        METH_VARARGS, pack__doc__},
  1321.     {"unpack",    struct_unpack,        METH_VARARGS, unpack__doc__},
  1322.     {NULL,        NULL}        /* sentinel */
  1323. };
  1324.  
  1325.  
  1326. /* Module initialization */
  1327.  
  1328. void
  1329. initstruct()
  1330. {
  1331.     PyObject *m, *d;
  1332.  
  1333.     /* Create the module and add the functions */
  1334.     m = Py_InitModule4("struct", struct_methods, struct__doc__,
  1335.                (PyObject*)NULL, PYTHON_API_VERSION);
  1336.  
  1337.     /* Add some symbolic constants to the module */
  1338.     d = PyModule_GetDict(m);
  1339.     StructError = PyErr_NewException("struct.error", NULL, NULL);
  1340.     if (StructError == NULL)
  1341.         return;
  1342.     PyDict_SetItemString(d, "error", StructError);
  1343. }
  1344.